package com.fjrz.bbxwj.main.access

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.TextPaint
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.blankj.utilcode.util.ToastUtils
import com.module.lemlin.view.LoadingDialog
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.fjrz.bbxwj.R
import com.fjrz.bbxwj.main.host.side.MainRichTextActivity
import com.fjrz.bbxwj.mode.vm.AccessViewModel
import com.module.lemlin.rxhttp.code
import com.module.lemlin.view.DialogHintPopup
import kotlinx.android.synthetic.main.activity_access_2.*

class AccessActivity : ViewModeActivity<AccessViewModel>() {

    companion object {

        private const val SPS_USER_AGREE = "SPS_USER_AGREE"
        fun open(activity: Activity) {
            val intent = Intent(activity, AccessActivity::class.java)
            activity.startActivity(intent)
        }
    }

    private val fragmentLifecycleCallbacks = object : FragmentManager.FragmentLifecycleCallbacks() {
        override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
            super.onFragmentResumed(fm, f)
            if (f is LoginFragment && motionLayout.currentState == R.id.end) {
                motionLayout.transitionToStart()
            }
        }

        override fun onFragmentCreated(
            fm: FragmentManager, f: Fragment, savedInstanceState: Bundle?
        ) {
            super.onFragmentCreated(fm, f, savedInstanceState)
            if (f !is LoginFragment && motionLayout.currentState == R.id.start) {
                motionLayout.transitionToEnd()
            }
        }
    }

    private val hintPopup: DialogHintPopup by lazy {
        DialogHintPopup(context = this,
            onConfirm = {
                hintPopup.dismiss()
                cbLoginAgree.isChecked = true
            },
            onCancel = {
                hintPopup.dismiss()
                cbLoginAgree.isChecked = false
                ActivityUtils.finishAllActivities()
            })
    }

    override val layoutResId: Int
        get() = R.layout.activity_access_2

    override fun viewModel(): AccessViewModel {
        return createViewModel()
    }

    override fun initView() {


        supportFragmentManager(
            LoginFragment.newInstance(), isToBackStack = false
        )

        supportFragmentManager.registerFragmentLifecycleCallbacks(
            fragmentLifecycleCallbacks, (true)
        )

        val agrees = "我已阅读并同意《用户协议》及《隐私政策》"
        tvLoginAgree.text = getSpannableStringUserAgree(agrees)
        tvLoginAgree.movementMethod = LinkMovementMethod.getInstance()

        val isUserAgree: Boolean = SPStaticUtils.getBoolean(SPS_USER_AGREE)
        if (!isUserAgree) {

            val content = "尊敬的倍倍星用户：我们尊重并保护您的个人隐私，为保障您的权益，" +
                    "请在注册登录前完整阅读并充分理解《用户协议》和《隐私协议》以帮助您了解维护自己隐私权的方式，" +
                    "一但您开始使用本软件服务，我们将按照上述内容中约定的权利和义务来处理您的个人信息。点击“同意”即表示您已阅读并接受上述内容之约定条款，" +
                    "然后我们将继续为您服务。"
            hintPopup.setTextTitle("用户协议和隐私政策")
                //.setTextUserAgree(getSpannableStringUserAgree("你可阅读《用户协议》和《隐私协议》了解详细信息。如你同意，请点击同意开始接受我们的服务。"))
                .setTextUserAgree(getSpannableStringUserAgree(content))
                .setTextCancel("不同意")
                .setTextConfirm("同意")
                .setBackPressEnable(false)
                .setOutSideDismiss(false)
                .showPopupWindow()
        }
        cbLoginAgree.isChecked = isUserAgree

        cbLoginAgree.setOnCheckedChangeListener { buttonView, isChecked ->
            SPStaticUtils.put(SPS_USER_AGREE, isChecked)
        }
    }

    private fun getSpannableStringUserAgree(agrees: String): SpannableString {
        val spannable = SpannableString(agrees)
        spannable.setSpan(
            object : ClickableSpan() {
                override fun onClick(widget: View) {
                    MainRichTextActivity.open(
                        activity = this@AccessActivity,
                        title = "用户协议",
                        name = "user_agreement_text"
                    )
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = ColorUtils.getColor(R.color.colorMain)
                    ds.isUnderlineText = false
                }
            },
            agrees.indexOf(string = "《"),
            agrees.indexOf(string = "》") + 1,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        spannable.setSpan(
            object : ClickableSpan() {
                override fun onClick(widget: View) {
                    MainRichTextActivity.open(
                        activity = this@AccessActivity,
                        title = "隐私协议",
                        name = "privacy_policy_text"
                    )
                }

                override fun updateDrawState(ds: TextPaint) {
                    super.updateDrawState(ds)
                    ds.color = ColorUtils.getColor(R.color.colorMain)
                    ds.isUnderlineText = false
                }
            },
            agrees.lastIndexOf(string = "《"),
            agrees.lastIndexOf(string = "》") + 1,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        return spannable
    }

    override fun initViewMode() {
        viewModel.userSmsLiveData.observe(this, Observer { response ->
            when (response.status) {
                Status.START -> LoadingDialog.show(
                    this as Context, resId = R.layout.dialog_load_style_1
                )
                Status.FAILURE -> {
                    LoadingDialog.dismiss()
                    toast(response.throwable?.code, response.throwable?.msg)
                }
                Status.SUCCESS -> {
                    LoadingDialog.dismiss()
                    toast(message = response.httpData?.msg ?: "发送成功")
                    response.httpData?.data?.let { any ->
                        if (any !is String)
                            return@Observer
                        supportFragmentManager.fragments.forEach {
                            if (it is CodeFragment) {
                                return@Observer
                            }
                        }
                        supportFragmentManager(CodeFragment.newInstance(any))
                    }
                }
            }
        })

        viewModel.userMeLiveData.observe(this, Observer { response ->
            when (response.status) {
                Status.START -> LoadingDialog.show(
                    this as Context, resId = R.layout.dialog_load_style_1
                )
                Status.FAILURE -> {
                    LoadingDialog.dismiss()
                    toast(response.throwable?.code, response.throwable?.msg)
                }
                Status.SUCCESS -> {
                    LoadingDialog.dismiss()
                    finish()
                }
            }
        })

    }

    private fun supportFragmentManager(fragment: Fragment, isToBackStack: Boolean = true) {
        val transaction: FragmentTransaction = supportFragmentManager.beginTransaction()
        if (isToBackStack) {
            transaction.setCustomAnimations(
                R.animator.slide_right_in, R.animator.slide_left_out,
                R.animator.slide_left_in, R.animator.slide_right_out
            )
            transaction.replace(R.id.frameAccessBody, fragment)
            transaction.addToBackStack(null)
        } else {
            transaction.add(R.id.frameAccessBody, fragment)
        }
        transaction.commit()
    }

    fun onClick(view: View) {
        when (view.id) {
            R.id.ivAccessBack -> onBackPressed()
            R.id.ivLoginWxBind -> {
//                supportFragmentManager(CodeFragment.newInstance("18396125445"))
            }
            R.id.tvLoginGetCode -> {
                if (!SPStaticUtils.getBoolean(SPS_USER_AGREE)) {
                    hintPopup.setTextTitle("用户协议和隐私政策")
                        .setTextUserAgree(getSpannableStringUserAgree("你可阅读《用户协议》和《隐私协议》了解详细信息。如你同意，请点击同意开始接受我们的服务。"))
                        .setTextCancel("不同意")
                        .setTextConfirm("同意")
                        .setBackPressEnable(false)
                        .setOutSideDismiss(false)
                        .showPopupWindow()
                } else {
                    viewModel.contentMobileLoginLiveData.value?.let {
                        viewModel.userSmsSend(it.toString(), "login")
                    }
                }
            }
            R.id.tvCheckCodeTime -> {
                viewModel.contentMobileLoginLiveData.value?.let {
                    viewModel.userSmsSend(it.toString(), "login")
                }
            }
            R.id.tvBindGetCode -> {
                viewModel.contentMobileBindLiveData.value?.let {
//                    supportFragmentManager(CodeFragment.newInstance(it.toString()))
                    viewModel.userSmsSend(it.toString(), "login")
                }
            }
        }
    }

    override fun onBackPressed() {
        if (SPStaticUtils.getBoolean(SPS_USER_AGREE)) {
            super.onBackPressed()
        } else {
            hintPopup.setTextTitle("用户协议和隐私政策")
                .setTextUserAgree(getSpannableStringUserAgree("你可阅读《用户协议》和《隐私协议》了解详细信息。如你同意，请点击同意开始接受我们的服务。"))
                .setTextCancel("不同意")
                .setTextConfirm("同意")
                .setBackPressEnable(false)
                .setOutSideDismiss(false)
                .showPopupWindow()
        }
    }

}